package auxiliar;

import modelo.Coordenadas;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class MyLocationListener implements LocationListener, OnCancelListener {
	
	private Context ctx;
	private LocationManager locationMgr;
	private boolean stopFlag;
	private ProgressDialog dialog;
	
	public MyLocationListener(Context ctx) {
	    this.ctx = ctx;
	}
	
	public void retrieveLocation() {

	    String locCtx = Context.LOCATION_SERVICE; 

	    locationMgr = (LocationManager) ctx.getSystemService(locCtx);

	    Criteria criteria = new Criteria();
	    criteria.setAccuracy(Criteria.ACCURACY_FINE);
	    criteria.setAltitudeRequired(false);
	    criteria.setBearingRequired(false);
	    criteria.setCostAllowed(true);
	    criteria.setPowerRequirement(Criteria.POWER_LOW);

	    String provider = locationMgr.getBestProvider(criteria, true);

	    locationMgr.requestLocationUpdates(provider, 0, 0, this);

	    Runnable showWaitDialog = new Runnable() {

	        public void run() {
	            while (!stopFlag) {
	                // Wait for first GPS Fix (do nothing until loc != null)
	            }
	            // After receiving first GPS Fix dismiss the Progress Dialog
	            dialog.dismiss();
	        }
	    };

	    dialog = ProgressDialog.show(ctx, "Por favor, aguarde...", "Recebendo dados do GPS...", true);
	    dialog.setCancelable(true);
	    dialog.setOnCancelListener(this);
	    Thread t = new Thread(showWaitDialog);
	    t.start();
	}

	public void onLocationChanged(Location location) {
		if (location != null) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();

			Coordenadas.setLatitude(String.valueOf(latitude));
			Coordenadas.setLongitude(String.valueOf(longitude));
			stopFlag = true;
		}
		locationMgr.removeUpdates(this);
	}
	
	public void onProviderDisabled(String provider) {
		Toast.makeText(null, "GPS Desligado", Toast.LENGTH_SHORT).show();
	}

	public void onProviderEnabled(String provider) {
		//Toast.makeText(null, "Gps Enabled", Toast.LENGTH_SHORT).show();
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	public void onCancel(DialogInterface dialog) {
	    stopFlag = true;
	    locationMgr.removeUpdates(this);
	}
}